package adminService

import (
	"errors"
	"gitee.com/yangguoliang001/go-gin-vue3/BO"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/config"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/gin-gonic/gin"
)

func (a *AdminService) Login(c *gin.Context, loginReq QO.LoginReqQO) (res BO.LoginBO, err error) {

	userInfo, err := a.adminDao.QueryAdminByUsername(loginReq.Username)

	// 查询用户失败，用户不存在
	if err != nil {
		response.Fail(c, code.AdminDetailError, code.Text(code.AdminDetailError), gin.H{"realErr": err})
		return BO.LoginBO{}, err
	}

	// 判断密码是否正确
	result := util.ComparePassword(userInfo.Password, loginReq.Password)

	if !result {
		response.Fail(c, code.AdminLoginError, "密码错误", gin.H{})
		return BO.LoginBO{}, errors.New("密码错误")
	}

	// 生成token
	token, err := util.ReleaseToken(userInfo)
	if err != nil {
		response.Fail(c, code.AdminLoginError, "生成Token失败", gin.H{"realErr": err})
		return BO.LoginBO{}, err
	}

	// 将用户信息存入 redis
	sessionUserInfo := BO.SessionUserInfo{
		UserId:   userInfo.Id,
		Username: userInfo.Username,
	}
	// 设置缓存
	// key: "go-gin-vue3:login-user:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEsImV4cCI6MTY3ODYzMDE1MiwiaWF0IjoxNjc4MDI1MzUyLCJpc3MiOiJ5Z2wiLCJzdWIiOiJ1c2VyIHRva2VuIn0.YJOG-0WnEhDo-k1sPgNdzE4ralfmI03KvQz5eTdDktw"
	// 127.0.0.1:6379> get "go-gin-vue3:login-user:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEsImV4cCI6MTY3ODYzMDE1MiwiaWF0IjoxNjc4MDI1MzUyLCJpc3MiOiJ5Z2wiLCJzdWIiOiJ1c2VyIHRva2VuIn0.YJOG-0WnEhDo-k1sPgNdzE4ralfmI03KvQz5eTdDktw"
	//"{\"userId\":1,\"username\":\"admin\"}"
	redisResult := a.cache.Set(config.RedisKeyPrefixLoginUser+token, string(util.Marshal(sessionUserInfo)), config.LoginSessionTTL)
	if redisResult.Err() != nil {
		response.Fail(c, code.AdminLoginError, code.Text(code.AdminLoginError), gin.H{"realErr": err})
		return BO.LoginBO{}, err
	}

	// 查询菜单
	menuData, err := a.MyMenu(c, userInfo.Id)
	if err != nil {
		response.Fail(c, code.AdminLoginError, code.Text(code.AdminLoginError), gin.H{"realErr": err})
		return BO.LoginBO{}, err
	}

	// 查询可访问接口信息
	actionJsonInfo, err := a.MyAction(c, userInfo.Id)
	if err != nil {
		response.Fail(c, code.AdminLoginError, code.Text(code.AdminLoginError), gin.H{"realErr": err})
		return BO.LoginBO{}, err
	}
	// 保存action数据，用于来拦截器中校验吗，接口权限
	redisResult = a.cache.Set(config.RedisKeyPrefixLoginUser+token+":actions", string(util.Marshal(actionJsonInfo)), config.LoginSessionTTL)
	if redisResult.Err() != nil {
		response.Fail(c, code.AdminLoginError, code.Text(code.AdminLoginError), gin.H{"realErr": err})
		return BO.LoginBO{}, err
	}

	return BO.LoginBO{
		Token:          token,
		MenuData:       &menuData,
		ActionJsonInfo: &actionJsonInfo,
	}, nil
}
